<template>
  <div>
    <div class="contentBox">
      <!-- <div class="contentBox-title">伙食费设置</div> -->
      <div>
        <Table border :columns="columns" :height="tableHeight" :data="data" :loading="loading"
          :size="vuex_config.tableSize">
          <template slot-scope="{ row, index }" :slot="it.slot" v-for="(it, idx) in dateStrList">
            <div style="padding: 10px 0">
              <span v-if="![1, 2, 3, 4, 5, 7].includes(index)">{{ row[it.slot] }}</span>
              <InputNumber :min="0" v-model="row[it.slot]" style="width: 100%; text-align: center !important"
                v-if="index == 1" disabled></InputNumber>
              <Select v-model="row[it.slot]" style="width: 100%" v-if="index == 2" @on-change="(value) => {
          changePrice(value, index, idx, it.slot);
        }
          ">
                <Option v-for="item in selectsList" :value="item.id" :key="item.id">{{ item.ovenClass }}({{ item.price
                  }})</Option>
              </Select>
              <InputNumber :min="0" v-model="row[it.slot]" style="width: 100%; text-align: center !important"
                v-if="index == 3" disabled></InputNumber>
              <InputNumber :min="0" :max="300" v-model="row[it.slot]" style="width: 100%; text-align: center !important"
                v-if="index == 4" @on-change="(value) => {
          changeFour(value, index, idx, it.slot);
        }
          "></InputNumber>
              <InputNumber :min="0" :max="50" v-model="row[it.slot]" style="width: 100%; text-align: center !important"
                v-if="index == 5" @on-change="(value) => {
          changeFour(value, index, idx, it.slot);
        }
          "></InputNumber>
              <InputNumber :min="0" :max="40000" v-model="row[it.slot]"
                style="width: 100%; text-align: center !important" v-if="index == 7" @on-change="(value) => {
          changeFour(value, index, idx, it.slot);
        }
          "></InputNumber>
            </div>
          </template>
        </Table>
      </div>
    </div>
    <div style="width: 100%; display: flex; justify-content: flex-end" class="mb_20">
      <!-- <Poptip>
        <cusButton class="mr_10" type="primary" v-if="this.form.make_type == 0"
          >配置食谱参数
        </cusButton>
        <div slot="content">
          <cusButton class="mb_10" type="primary" @onClick="skit"
            >食材配置</cusButton
          >
          <cusButton type="primary" @onClick="gotoDisConf">菜肴配置</cusButton>
        </div>
      </Poptip> -->
      <cusButton class="mr_20" type="primary" @onClick="submit">生成食谱</cusButton>
    </div>
    <!-- <div class="operBox" style="width: calc(100% - 250px);">
            <Button type="error" class="mr_24" @click="backTop">返回</Button>
            <Button type="success" class="mr_24" @click="saveBtn">保存</Button>
        </div> -->
  </div>
</template>
<script>
import {
  aimealstandard,
  getboardrate,
  unitStrength,
  updateaimealstandard,
  checkDish,
} from "@/api/business/dishesModule";

export default {
  props: {
    form: {
      type: Object,
    },
  },
  components: {},
  data() {
    return {
      loading: false,
      data: [],
      columns: [
        {
          title: "",
          key: "name",
          width: 188,
          align: "center",
        },
      ],
      dateList: [], // 一周日期集合
      dateStrList: [
        { name: "星期一", slot: "monday" },
        { name: "星期二", slot: "tuesday" },
        { name: "星期三", slot: "wednesday" },
        { name: "星期四", slot: "thursday" },
        { name: "星期五", slot: "friday" },
        { name: "星期六", slot: "saturday" },
        { name: "星期日", slot: "sunday" },
      ],
      tableLeftName: [
        { name: "伙食标准(元/天)", key: "default_standard", id: 1 },
        { name: "军粮差价", key: "storesDifference" },
        { name: "其他补贴", key: "elseSubsidy" },
        { name: "合计", key: "boardTotal" },
        { name: "计划伙食费(元/人/天)", key: "practical_boardwages" },
        { name: "伙食费浮动比例(%)", key: "boardwages_sliding" },
        { name: "热量(kcal/人/天)", key: "energy" },
        { name: "就餐人数(人)", key: "repast_numer" },
      ],
      tableHeight: 0,
      selectsList: [],
    };
  },
  whatch: {},
  mounted() { },
  methods: {
    checkError(data) {
      if (data.retCode == 2888 && data.retMsg == "菜肴数量严重不足，无法智能生成食谱!") {
        let content = "";
        data.data.map((it) => {
          content += `<p style="margin-top:5px">${it}</p>`;
        });
        this.$Modal.warning({
          title: data.retMsg,
          content: content,
          width: "750",
          okText: "关闭",
        });
      } else {
        let content = "";
        data.data.map((it) => {
          content += `<p style="margin-top:5px">${it}</p>`;
        });
        this.$Modal.confirm({
          title: data.retMsg,
          content: content,
          width: "750",
          okText: "继续生成",
          onOk: () => {
            this.saveBtn();
          },
        });
      }
    },
    submit() {
      this.$emit("validate");
    },
    checkDish() {
      console.log('具体数据', this.form);
      if (this.form.make_type) {
        this.saveBtn();
      } else {
        checkDish().then((res) => {
          if (res.retCode == 2000) {
            this.saveBtn();
          } else if (res.retCode == 2888) {
            this.checkError(res);
          } else {
            this.$Message.error(res.Msg);
          }
        });
      }
    },
    onit(ovenClass) {
      if(ovenClass || ovenClass == 0) {
        this.form.ovenClass = ovenClass
      } else {
        this.$Message.error('没有伙食灶')
        return
      }
      console.log('form值', this.form);
      this.getCurrentWeek(this.form.stopDate);
      this.aimealstandardApi().then(() => {
        // 替换就餐人数
        this.unitStrengthApi();
      });
      console.log("11");
      this.getboardrateApi();
    },
    // 配置食谱参数页面跳转
    skit() {
      this.$router.push({
        name: "食材配置",
      });
    },
    gotoDisConf() {
      this.$router.push({
        name: "菜肴配置",
      });
    },
    // 获取就餐人数 --接口
    unitStrengthApi() {
      return new Promise((resolve) => {
        unitStrength({}).then((res) => {
          this.loading = false;
          if (res.retCode == 2000 && res.data) {
            this.$set(this.data[7], "monday", res.data[0].registered);
            this.$set(this.data[7], "tuesday", res.data[0].registered);
            this.$set(this.data[7], "wednesday", res.data[0].registered);
            this.$set(this.data[7], "thursday", res.data[0].registered);
            this.$set(this.data[7], "friday", res.data[0].registered);
            this.$set(this.data[7], "saturday", res.data[0].registered);
            this.$set(this.data[7], "sunday", res.data[0].registered);
            resolve();
          }
        });
      });
    },
    // 获取伙食费标标准 --接口
    aimealstandardApi() {
      let form = this.$cu.deepClone(this.form);
      // let formClone = JSON.parse(JSON.stringify(this.form));
      console.log('克隆的数据', form, this.form);
      this.loading = true;
      return new Promise((resolve) => {
        aimealstandard({
          strength: form.strength,
          boardId: form.ovenClass,
          typeMeal: form.make_type == 0 ? 1 : 0,
          region: form.type,
        }).then((res) => {
          if (res.retCode == 2000 && res.data) {
            this.data = [];
            this.tableLeftName.forEach((item, index) => {

              this.data.push({
                name: item.name,
                key: item.key,
                id: res.data[item.key][0],
                monday: res.data[item.key][1],
                tuesday: res.data[item.key][2],
                wednesday: res.data[item.key][3],
                thursday: res.data[item.key][4],
                friday: res.data[item.key][5],
                saturday: res.data[item.key][6],
                sunday: res.data[item.key][7],
              });

            });
            console.log('2234', this.data);
            resolve();
          }
          if (res.retCode != 2000) {
            this.$Message.error(res.retMsg);
          }
        });
      });
    },
    // 获取其他补贴下拉列表 --接口
    getboardrateApi() {
      return new Promise((resolve) => {
        getboardrate({
          boardRateType: 3,
        }).then((res) => {
          if (res.retCode == 2000) {
            this.selectsList = res.data.map((item) => {
              return {
                ovenClass: item.ovenClass,
                id: item.id,
                price: this.form.type == 0 ? item.generalAreas : item.specialArea,
              };
            });
            resolve();
          }
          if (res.retCode != 2000) {
            this.$Message.error(res.retMsg);
          }
        });
      });
    },
    // 获取本周日期组件处理
    getCurrentWeek(date) {
      let nowData = new Date(date); //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
      let currentDay = nowData.getDay();
      if (currentDay == 0) {
        currentDay = 7;
      }

      let beforweek = [],
        afterWeek = [];
      for (let i = 1; i <= 7; i++) {
        if (currentDay - i >= 0) {
          let DayTime = nowData.getTime() - (currentDay - i) * 24 * 60 * 60 * 1000;
          beforweek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        } else {
          let DayTime = nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000;
          afterWeek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        }
      }
      afterWeek = afterWeek.reverse();
      this.dateList = [...beforweek, ...afterWeek];
      if (this.dateList.length) {
        (this.columns = [
          {
            title: "",
            key: "name",
            width: 188,
            align: "center",
          },
        ]),
          this.dateList.forEach((item, index) => {
            this.columns.push({
              title: `${item}(${this.dateStrList[index].name})`,
              align: "center",
              key: `${this.dateStrList[index].slot}`,
              slot: `${this.dateStrList[index].slot}`,
            });
          });
      }
    },
    // 价格选项切换
    changePrice(value, index1, index2, slot) {
      if (!value) return;

      let subsidies = this.selectsList.filter((item) => {
        return item.id == value;
      });

      this.$set(this.data[index1], slot, value);
      // 合计为其他补贴，+ 军粮差价 + 伙食费标准
      let aNum = parseFloat(
        (
          subsidies[0].price +
          this.data[index1 - 1][slot] +
          this.data[index1 - 2][slot]
        ).toFixed(2)
      );
      this.$set(this.data[index1 + 1], slot, aNum);
      this.$set(this.data[index1 + 2], slot, aNum);
    },
    changeFour(value, index1, index2, slot) {
      this.$set(this.data[index1], slot, value);
    },
    // 返回
    backTop() {
      this.$cu
        .dialog({
          content: "是否确认返回？确认返回后，您此次操作数据将不会保留",
        })
        .then(() => {
          this.$router.go(-1);
        });
    },
    // 保存
    saveBtn() {
      let form = this.$cu.deepClone(this.form);
      let saveArr = this.$cu.deepClone(this.data);
      let saveItem = {
        boardId: this.form.ovenClass,
        region: this.form.type,
        typeMeal: form.make_type == 0 ? 1 : 0,
        labourId: this.form.strength,
      };
      saveArr.forEach((item, index) => {
        if (
          item.key == "storesDifference" ||
          item.key == "boardTotal" ||
          item.key == "practical_boardwages"
        ) {
          saveItem[item.key] = [
            item.id,
            parseFloat(item.monday.toFixed(2)),
            parseFloat(item.tuesday.toFixed(2)),
            parseFloat(item.wednesday.toFixed(2)),
            parseFloat(item.thursday.toFixed(2)),
            parseFloat(item.friday.toFixed(2)),
            parseFloat(item.saturday.toFixed(2)),
            parseFloat(item.sunday.toFixed(2)),
          ];
        } else {
          saveItem[item.key] = [
            item.id,
            item.monday,
            item.tuesday,
            item.wednesday,
            item.thursday,
            item.friday,
            item.saturday,
            item.sunday,
          ];
        }
      });
      console.log(saveItem);
      updateaimealstandard(saveItem).then((res) => {
        if (res.retCode == 2000) {
          this.$Message.success("保存成功,正在前往生成食谱");
          setTimeout(() => {
            form.peopleList = saveItem["repast_numer"];
            form.peopleList.splice(0, 1);
            form.cateringModelId = null;
            form.meal_plan_id = 0;
            form.begian_time = form.startDate;
            form.end_time = form.stopDate;
            form.boardId = form.ovenClass;
            form.make_type = form.make_type == 0 ? 1 : 0; // 0 代表手工创建类型 1 代表智能食谱
            console.log(form);
            this.$router.push({
              path: `/createHandmade/createHandmadeThree`,
              query: {
                form: JSON.stringify(form),
              },
            });
          }, 1000);
        }
        if (res.retCode != 2000) {
          this.$Message.error(res.retMsg);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ivu-input-number-input {
  text-align: center !important;
}

.contentBox {
  min-height: 555px;
  background: #fff;
  border-radius: 2px;
  padding: 24px;

  // margin-bottom: 80px;
  &-title {
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 16px;
    color: rgba(0, 0, 0, 0.65);
  }
}

.operBox {
  position: fixed;
  bottom: 0;
  right: 0;
  height: 88px;
  display: flex;
  flex-direction: row-reverse;
  // width: 100%;
  background: #ffffff;
  align-items: center;
  padding: 0 40px;
  box-shadow: 0px -1px 6px 0px rgba(0, 0, 0, 0.12), 0px -1px 2px -2px rgba(0, 0, 0, 0.16);
}
</style>
